import { memo, useRef, useState } from "react";
import { Carousel } from "antd";
import IconArrowLeft from "@/assets/svg/icon-arrow-left";
import IconArrowRight from "@/assets/svg/icon-arrow-right";
import { SectionRoomItemWapper } from "./style";
import Indicator from "../indicator";
import classNames from "classnames";

const SectionRoomItem = memo((props) => {
  const { data, width = "20%", emit = undefined } = props;

  const [selectIndex, setSelectIndex] = useState(0);
  const sliderRef = useRef();

  // 切换图片
  function handleControl(isNext, event) {
    // 阻止冒泡
    event.stopPropagation();
    // 滚动
    isNext ? sliderRef.current.next() : sliderRef.current.prev();
    // 计算索引
    let index = isNext ? selectIndex + 1 : selectIndex - 1;
    if (index > data.picture_urls.length - 1) index = 0;
    if (index < 0) index = data.picture_urls.length - 1;
    setSelectIndex(index);
  }

  // 跳转详情页
  function handleDetail() {
    if (emit) emit(data);
  }

  const pictureElement = (
    <div className="cover">
      <img src={data.picture_url} alt="" />
    </div>
  );

  const sliderElement = (
    <div className="slider">
      <div className="control">
        <div
          className="btn left"
          onClick={(e) => {
            handleControl(false, e);
          }}
        >
          <IconArrowLeft width="30" height="30" />
        </div>
        <div
          className="btn right"
          onClick={(e) => {
            handleControl(true, e);
          }}
        >
          <IconArrowRight width="30" height="30" />
        </div>
      </div>
      <div className="indicator">
        <Indicator selectIndex={selectIndex}>
          {data.picture_urls?.map((item, index) => {
            return (
              <div className="item" key={item}>
                <span className={classNames("dot", { active: selectIndex === index })}></span>
              </div>
            );
          })}
        </Indicator>
      </div>
      <Carousel dots={false} ref={sliderRef}>
        {data?.picture_urls?.map((item) => {
          return (
            <div className="cover" key={item}>
              <img src={item} alt="" />
            </div>
          );
        })}
      </Carousel>
    </div>
  );

  return (
    <SectionRoomItemWapper width={width} onClick={handleDetail}>
      <div className="inner">
        {data.picture_urls ? sliderElement : pictureElement}
        <div className="desc" style={{ color: data.verify_info?.text_color || "#39576a" }}>
          {data.verify_info.messages.join(" · ")}
        </div>
        <div className="name">{data.name}</div>
        <div className="price">￥{data.price}/晚</div>
        <div className="bottom"></div>
      </div>
    </SectionRoomItemWapper>
  );
});

export default SectionRoomItem;
